<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use think\Db;
use think\Controller;

class IndexController extends BaseController {

	function index(){
		//dump(config('wxpay')['APPID']);exit;	
		//获取商品分类
		$cate_list = db('good_cate')->select();
		$this->assign('cate_list', $cate_list);
		
		$this->assign('user_id', session('user_id'));
		return $this->fetch();
	}
	
	//获取商品分类
	function getgoodcate(){
	
		$agent_id = input('agent_id');
		if(!$agent_id){
			$agent_id = 1;
		}
		$where['agent_id'] = $agent_id;
		//分类
		$cate_list = db('good_cate')->where($where)->select();
		$type = array();
		foreach($cate_list as $k=>$v){
			$type[$v['id']]=$v;
		}
		$data['type'] = $cate_list;
		$where['status'] = 1;
		$where['is_on_sale'] = 1;
		//$where['stock'] => '0';
		//产品
		$field="goods_id,goods_sn,goods_name,sales,stock,logo,cate_id,cate2_id,unit,is_on_sale,sort,sale_price,content,status,trade_id,is_recommend,fen_price,tui_id,tui_price";
		$goods = db("goods")->field($field)->where($where) ->where('stock','>',0)->select();	
		for ($i = 0; $i < count($goods); $i++) {
			$goods[$i]['content'] = html_entity_decode($goods[$i]['content']);
		}
		$res = array();
		$ress = array();
		$restj = array();
		foreach($goods as $k=>$v){
		 	$res[$v['trade_id']][]=$v;
			$ress[$v['goods_id']][]=$v;
			if($v['is_recommend']==1){
				$restj[$v['goods_id']][]=$v;
			}
		}
		
		$data['res'] = $goods;
		return json(['type'=>$type,'res'=>$res,'ress'=>$ress,'restj'=>$restj,'data'=>$data]);
	}

	public function login() {
		if(request()->isPost()){
			//验证码
			$result = $this->check_code($_POST['mobile'], input('code'), '用户注册');
			if ($result != 1) {
				$this->error('验证码错误!');
			}
			
			//检查是否注册
			$user_info = db('member')->where('mobile',$_POST['mobile'])->find();
			if($user_info){
				return json(['code'=>402,'msg'=>'该号码已注册']);
			}else{
				$data['mobile'] 	= $_POST['mobile'];
				$data['pid1'] 	= $_POST['pid1'];
				if($_POST['pid1']){
					$mfo = db('member')->where('user_id',$_POST['pid1'])->find();
					if($mfo && $mfo['pid1']){
						$data['pid2'] 	= $mfo['pid1'];
					}
				}
				$data['update_time'] 	= now_time();
				if(session("openid")){
					$rest = db('member')->where('open_id',session("openid"))->update($data);
				}else{
					return 0 ;
				}
				if($rest){
					return json(['code'=>200,'msg'=>'绑定成功','url'=>'/index/index/index']);
				}else{
					return json(['code'=>405,'msg'=>'绑定失败']);
				}
			}
		}
		return $this->fetch();
	}
	public function login22() {
		if(session('user_id')){
			$this->redirect('index/member/index');
		}
		if (request()->isPost()) {
			$user_info = db('member')
							->where('mobile',input('mobile'))
							->where('password',md5_salt(input('password')))
							->find();
			if($user_info){
				if($user_info['status'] == 2){
					return json(['code'=>403,'msg'=>'账号已冻结']);
				}else{
					session('user_id',$user_info['user_id']);
					session('user_info',$user_info);	
					return json(['code'=>200,'msg'=>'登录成功']);
				}
			}else{
				return json(['code'=>402,'msg'=>'登录失败']);	
			}
		}
		return $this->fetch();
	}
	
	/**
     * 获取验证码
     * 注意防盗刷
     * 
     */
    function verify_code(){
    	if(request()->isPost()){
    		$user_ip = $_SERVER["REMOTE_ADDR"];
    		
    		$code_info  =db('verify_code')->where('user_ip',$user_ip)->whereTime('add_time', 'today')->select();
    		
    		if(count($code_info)>10){
    			return json(['code'=>402,'msg'=>'ip异常']);
    		}else{
    			
    			return get_code($_POST['mobile'],$user_ip);
    		}
    	}
    }

	/**
	 * 注册:第一步
	 */
	function register() {
		
		if(request()->isPost()){
			//验证码
			$result = $this->check_code($_POST['mobile'], input('code'), '用户注册');
			if ($result != 1) {
				$this->error('验证码错误!');
			}
			
			//检查是否注册
			$user_info = db('member')->where('mobile',$_POST['mobile'])->find();
			if($user_info){
				return json(['code'=>402,'msg'=>'该号码已注册']);
			}else{
				$data['mobile'] 	= $_POST['mobile'];
				$data['password'] 	= md5_salt($_POST['password']);
				$data['add_time'] 	= now_time();
				
				$rest = db('member')->insertGetId($data);
				if($rest){
					$user_info = db('member')->find($rest);
					session('user_id',$user_info['user_id']);	
					return json(['code'=>200,'msg'=>'注册成功','url'=>'/index/member/index']);
				}else{
					return json(['code'=>405,'msg'=>'注册失败']);
				}
			}
		}
		
		return $this->fetch();
	}
	
	/**
	 * 忘记密码
	 */
	public function forget() {
		if ($this->request->isPost()) {
			$password = input('password');
			$mobile = input('mobile');
			$code = input('code');
			if (!is_numeric($mobile) || !is_numeric($code)) {
				$this->error('非法访问');
			}
			$result = $this->check_code($mobile, $code, '找回密码');
			if ($result != 1) {
				$this->error('验证码错误或过期');
			}
			//手机号是否存在
			$p_member = db('member')->where('mobile', $mobile)->find();
			if (!$p_member) {
				$this->error('用户或手机号码不存在');
			}
			$data2['password'] = md5_salt($password);
			$result = db('member')->where("id", $p_member['id'])->update($data2);
			if ($result !== false) {
				$this->success('修改成功，请登录', url('index/login'));
			} else {
				$this->error('修改失败');
			}
		} else {
			return $this->fetch();
		}
	}

	public function regist_code($mobile) {
		return $this->get_code(config('aliyun'), config('aliyun.regist_id'), $mobile, "用户注册");
	}

	public function forget_code($mobile) {
		return $this->get_code(config('aliyun'), config('aliyun.forget_id'), $mobile, "找回密码");
	}
	
	public function logout() {
		session('user_id', null);
		return json(['code'=>200,'msg'=>'退出成功']);
	}
	
	public function xy() {
		return $this->fetch();
	}

	//跳转订单支付页面
	public function goorder(){
		
		$agent_id = input('agent_id');
		$params = input("");
		$goods = isset($params['goods'])?$params['goods']:null;//商品
		var_dump(input('price'));exit;
		session('goods',$goods);
		session('price',input('price'));
		$data['goods'] = $goods;
		$data['price'] = input('price');
//		return json(['code'=>200,'msg'=>'操作成功','data'=>$data]);
	}
	
	public function pay_success(){
		return $this->fetch();
	}
	
	/**
	 * 发送短信
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	protected function get_code($config, $template_id, $mobile, $message) {
		$code = rand(1000, 9999);
		$data['mobile'] = $mobile;
		$data['code'] = $code;
		$data['message'] = $message;
		$data['add_time'] = now_time();
		include_once ('././extend/smsapi/smsDemo.php');
		$msg = sendSms($config, $template_id, $mobile, 'code', $code);
		if ($msg->Message == "OK") {
			$data['result'] = '发送成功';
			db('verify_code')->insert($data);
			$this->success('发送成功');
		} else {
			$err = $msg->Message;
			$data['result'] = '发送失败 - ' . $err;
			db('verify_code')->insert($data);
			$this->error('发送失败' . $err);
		}
	}
	
	
	protected function check_code($mobile, $code, $message) {
		$where['mobile'] = $mobile;
		$where['message'] = $message;
		//'用户注册';
		$where['result'] = '发送成功';
		$result = db('verify_code')->where($where)->order('add_time desc')->find();
		if ($result) {
			//判断是否正确
			if ($code == $result['code']) {
				// 10分钟有效期
				if (time() < strtotime($result['add_time']) + 600) {
					return 1;
				} else {
					return 2;
				}
			}
		} else {
			return -1;
		}
	}
	
	//校验商品库存
	function check_stock(){
		$good=db("goods")->where("goods_id",input('goods_id'))->find();
		if($good){
			if($good['stock']>input("nums")){
				return json(['code'=>200]);
			}else{
				return json(['code'=>400,'msg'=>'商品库存不足！还剩下'.$good['stock'].'份了']);
			}
		}else{
			return json(['code'=>404,'商品不存在']);
		}
	}
	
}
